from django.shortcuts import render, redirect
from question.models import *
from hashlib import md5
from django.conf import settings
from django.http import JsonResponse
import random
from django.db import transaction

# Create your views here.
def loLogin(request):
    msg = ''
    # 登录判断是否已经登录过了
    if request.session.get('user'):
        return redirect('/loadmin/index/')
    # 根据提交方式执行代码
    if request.method == 'POST':
        account = request.POST.get('account', '').strip()
        pwd = request.POST.get('pwd', '').strip()
        # 判断账号密码不能为空
        if not (account and pwd):
            msg = '用户名或者密码不能为空！'
        else:
            # 通过orm的get方法判断是否存改用户
            try:
                user = User.objects.get(account=account)
                # hash密码产生新的随机字符串
                newPwd = md5(pwd.encode('utf-8')).hexdigest()
                # 判断密码是否相等
                if newPwd == user.pwd:
                    request.session['user'] = {'id': user.id, 'name': user.name, 'type': user.type}
                    return redirect('/loadmin/index/')
                else:
                    msg = '密码错误，请重新输入！'
            except Exception as e:
                msg = '该用户不存在'
    return render(request, 'login.html', {'msg': msg})


def loginOut(request):
    request.session.clear_expired()
    request.session.clear()
    # request.session.delete("user")
    return redirect('/loadmin/')


def checkLogin(func):
    def inner(request, *args, **kwargs):
        if not request.session.get('user', None):
            return redirect('/loadmin/')
        return func(request, *args, **kwargs)
    return inner

@checkLogin
def index(request):
    user = request.session['user']
    menus = settings.LOMENU
    # 获取配置文件设置的管理菜单
    menus = menus['teacher'] if request.session['user']['type'] == '讲师' else menus['admin']
    # print(menus)
    return render(request, 'index.html', {'menus': menus, 'user': user})

@checkLogin
def main(request):
    loginNum = random.randint(1,50)
    # 总题
    questionNum = Subject.objects.count()
    # 待解决
    question_0_Num = Subject.objects.filter(state=0).count()
    # 已解决
    questionNum_1_num = Subject.objects.filter(state=1).count()

    return render(request, 'main.html',
                  {
                      'loginNum': loginNum,
                      'questionNum': questionNum,
                      'question_0_Num': question_0_Num,
                      'questionNum_1_num': questionNum_1_num,
                   })

@checkLogin
def users(request):
    users = User.objects.all().order_by('-id')
    users_count = users.count()
    return render(request, 'users.html', {'users': users, 'users_count': users_count})

@checkLogin
def userAdd(request):
    if request.method == 'POST':
        account = request.POST.get('account', None)
        realName = request.POST.get('realName', None)
        type = request.POST.get('type', None)
        pwd = request.POST.get('pwd', None)
        agpwd = request.POST.get('agpwd', None)
        subjectIds = request.POST.getlist('subjectId[]', None)
        if not (account and pwd and agpwd):
            return JsonResponse({'code': 1004, 'msg': '用户信息不完整，请重新填写！'})
        if agpwd != pwd:
            return JsonResponse({'code': 1005, 'msg': '两次密码不等！'})

        try:

            pwd = md5(pwd.encode('utf-8')).hexdigest()
            user = User.objects.create(account=account, pwd=pwd, name=realName, type=type)
            # user.subjectrole.set(list(map(int, subjectIds)))
            if subjectIds: user.roles.add(*subjectIds)

            return JsonResponse({'code': 200, 'msg': '操作成功！'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

    # 获取所有课程
    subjects = SubjectRole.objects.all().order_by('-id')
    return render(request, 'user_add.html', {'subjects': subjects})

@checkLogin
def userEdit(request, id):

    if request.method == 'POST':
        realName = request.POST.get('realName', None)
        type = request.POST.get('type', None)
        pwd = request.POST.get('pwd', None)
        agpwd = request.POST.get('agpwd', None)
        subjectIds = request.POST.getlist('subjectId[]', None)

        try:
            userInfo = User.objects.get(id=id)
            # 当两个密码同时存在时才修改密码
            if pwd and agpwd :
                if agpwd != pwd:
                    return JsonResponse({'code': 1005, 'msg': '两次密码不等！'})
                userInfo.pwd = md5(pwd.encode('utf-8')).hexdigest()

            userInfo.name = realName
            userInfo.type = type
            # 事务
            with transaction.atomic():
                userInfo.save()
                # 判断是否是讲师，不是把课程清空，是就更新关系
                if subjectIds and type == '讲师':
                    print(subjectIds)
                    userInfo.roles.set(subjectIds)
                else:
                    userInfo.roles.clear()
            return JsonResponse({'code': 200, 'msg': '操作成功！'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

    user = User.objects.get(id=id)
    # 获取所有课程
    subjects = SubjectRole.objects.all().order_by('-id')
    return render(request, 'user_edit.html', {'subjects': subjects, 'user': user})

@checkLogin
def userDel(request):
    id = request.POST.get('id', None)
    if not (id and subjects):
        return JsonResponse({'code': 1003, 'msg': '要删除的用户不存在！'})
    try:
        user = User.objects.get(id=id)
        # 删除用户
        user.delete()
        return JsonResponse({'code': 200, 'msg': '操作成功！'})
    except Exception as e:
        return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

@checkLogin
def subjects(request):
    """
    课程展示和添加课程
    :param request:
    :return:
    """
    if request.method == 'POST':
        subjects = request.POST.get('subjects', None).strip()
        if not subjects:
            return JsonResponse({'code': 1002, 'msg': '课程不能为空！'})

        try:
            # 处理批量对象列表
            subject_objs = []
            for subject in subjects.split(','):
                subject_objs.append(SubjectRole(role=subject))
            # 批量添加
            SubjectRole.objects.bulk_create(subject_objs)

            return JsonResponse({'code': 200, 'msg': '操作成功！'})
        except Exception as e:
            return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

    subjects = SubjectRole.objects.all().order_by('-id')
    subjects_count = subjects.count()
    return render(request, 'subjects.html', {"subjects": subjects, "subjects_count": subjects_count})

@checkLogin
def subjectsDel(request):
    id = request.POST.get('id', None)
    if not (id and subjects):
        return JsonResponse({'code': 1003, 'msg': '要删除的课程不存在！'})
    try:
        SubjectRole.objects.get(id=id).delete()
        return JsonResponse({'code': 200, 'msg': '操作成功！'})
    except Exception as e:
        return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

@checkLogin
def subjectsEdit(request):
    id = request.POST.get('id',None)
    subjectRole = request.POST.get('reRole', None)
    if not (id and subjectRole):
        return JsonResponse({'code': 1003, 'msg': '要修改的课程id或者名称不能为空！'})
    try:
        subjectObj = SubjectRole.objects.get(id=id)
        subjectObj.role = subjectRole
        subjectObj.save()
        return JsonResponse({'code': 200, 'msg': '操作成功！'})
    except Exception as e:
        return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})


@checkLogin
def questions(request):
    # 获取要展示的当前分页
    page = int(request.GET.get('page', 1))

    state = request.GET.get('state', None)
    where = {}
    # 获取登录用户信息
    userInfo = request.session.get('user', {})
    if not state is None:
        where['state'] = state
    if request.session['user']['type'] == '讲师':
        where['teacher_id'] = userInfo['id']

    # 开始位置
    start_index = (page - 1) * 9
    # 结束位置
    end_index = page * 9
    # 根据条件获取对应题目信息
    subjects = Subject.objects.filter(**where).order_by('-id')[start_index:end_index]
    subjects_count = Subject.objects.filter(**where).count()
    # 获取所有讲师为题目分配指定讲师
    teachers = User.objects.values('id', 'name').filter(type='讲师').order_by('-id')

    # 总页数
    all_pages = subjects_count / 9
    if subjects_count % 9 > 0: all_pages += 1

    return render(request, 'questions.html', {'subjects': subjects, 'subjects_count': subjects_count, 'teachers': teachers, 'userInfo': userInfo, 'all_pages': all_pages, 'page': page})

@checkLogin
def questionAdd(request):
    if request.method == 'POST':
        title = request.POST.get('title', None)
        subject_str = request.POST.get('subject', None)
        answer = request.POST.get('answer', None)
        company = request.POST.get('company', None)
        address = request.POST.get('address', None)
        if not (title and subject_str):
            return JsonResponse({'code': 1006, 'msg': '题目信息不完整！'})
        try:
            Subject.objects.create(
                title=title,
                answer=answer,
                company=company,
                address=address,
                student_id='lanou',
                student_name='蓝鸥',
                subject=subject_str,
                classroom='lanou',
                teacher= User.objects.get(id=1) if answer else None,
                state=(1 if answer else 0)  # 根据答案是否添加设置值
            )
            return JsonResponse({'code': 200, 'msg': '操作成功！'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

    subjects = SubjectRole.objects.all().order_by('-id')
    return render(request, 'question_add.html',{'subjects': subjects})

@checkLogin
def questionEdit(request, id):
    if request.method == 'POST':
        title = request.POST.get('title', None)
        subject_str = request.POST.get('subject', None)
        answer = request.POST.get('answer', None)
        company = request.POST.get('company', None)
        address = request.POST.get('address', None)
        if not (title and subject_str):
            return JsonResponse({'code': 1006, 'msg': '题目信息不完整！'})
        try:
            subject = Subject.objects.get(id=id)
            subject.title=title
            subject.answer=answer
            subject.company=company
            subject.address=address
            subject.subject=subject_str
            # 没有指派讲师并且答案不为空时
            if not subject.teacher_id and answer:
                subject.teacher= User.objects.get(id=1)
            subject.state=(1 if answer else 0)  # 根据答案是否添加设置值
            subject.save()

            return JsonResponse({'code': 200, 'msg': '操作成功！'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

    # 要修改的题目
    subject = Subject.objects.get(id=id)
    # 所有学科
    subjects = SubjectRole.objects.all().order_by('-id')
    return render(request, 'question_edit.html', {'subject': subject, 'subjects': subjects})

@checkLogin
def questionDel(request):
    id = request.POST.get('id', None)
    if not (id and subjects):
        return JsonResponse({'code': 1007, 'msg': '要删除的题目不存在！'})
    try:
        Subject.objects.get(id=id).delete()
        return JsonResponse({'code': 200, 'msg': '操作成功！'})
    except Exception as e:
        return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

@checkLogin
def questionSetTeacher(request):
    teacher_id = request.POST.get('teacher_id', None)
    subject_id = request.POST.get('subject_id', None).strip().strip(',')
    if not (teacher_id and subject_id):
        return JsonResponse({'code': 1008, 'msg': '分配讲师时信息不完整！'})
    try:
        subjects = Subject.objects.filter(id__in=subject_id.split(','))
        for subject in subjects:
            subject.teacher_id = teacher_id
            subject.save()
        return JsonResponse({'code': 200, 'msg': '操作成功！'})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})

@checkLogin
def questionImport(request):
    questionsFile = request.FILES.get('questionFile', None)
    if not questionsFile:
        return JsonResponse({'code': 1009, 'msg': '请选择要上传到文件！'})
    try:
        import pandas as pd
        if not questionsFile.name.split('.')[-1] in ['xlsx', 'xlsm', 'xlsb', 'xltx', 'xls', 'xlt', 'xls']:
            # data = pd.read_csv(questionsFile, header=0, encoding='utf-8')
            return JsonResponse({'code': 1010, 'msg': '您上传的文件格式暂不支持，期待后续开发！'})
        else:
            data = pd.read_excel(questionsFile, header=0, encoding='utf-8')

        subjects = []
        # 事务
        with transaction.atomic():
            for index, row in data.iterrows():
                answer = row['answer'] if row['answer'] == 'nan' else None
                subjects.append(Subject(
                    title=row['title'],
                    answer=answer,
                    company=row['company'],
                    address=row['address'],
                    student_id='lanou',
                    student_name='蓝鸥',
                    subject=SubjectRole.objects.get(role__icontains=row['subject']),
                    classroom='lanou',
                    teacher=User.objects.get(id=1) if answer else None,
                    state=(1 if answer else 0)  # 根据答案是否添加设置值
                ))
            Subject.objects.bulk_create(subjects)

        return JsonResponse({'code': 200, 'msg': '操作成功！'})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1001, 'msg': '操作失败，请联系管理员！'})